# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from django import newforms as forms
from django.contrib.auth.models import User
from apps.core.models.element import Element
from apps.core.models.section import Section
from apps.core.backend.views.forms import base_form

class ElementForm(base_form.BaseForm):
    # Parametri descrittivi
    title = forms.CharField(label='Titolo')
    subtitle = forms.CharField(label='Sottotitolo', required=False)
    order = forms.CharField(label="Ordinamento")
    publication_start = forms.DateTimeField(label="Inizio Pubblicazione", required=False)
    publication_end = forms.DateTimeField(label="Fine Pubblicazione", required=False)  
    # SEO Metadata
    slug = forms.CharField(label='Slug', required=False)
    keywords = forms.CharField(required=False)
    metatags = forms.CharField(required=False)
    # Dipendenze
    section = forms.ChoiceField(label='Sezione')
    id = None
    
    def __init__(self, *args, **kwargs):
        self.SECTION_CHOICES = [('', '------')] + [(s.id, s.name) for s in Section.objects.all()]
        self.base_fields['section'].choices = self.SECTION_CHOICES
        try:
            self.id = kwargs['initial']['related_element_id']
            el = Element.objects.get(id=self.id)
        except:
            el = None
        super(ElementForm, self).__init__(el, *args, **kwargs)
            
    def save(self, tp, *args, **kwargs):
        if self.id == None :
            e = Element()
        else:
            e = Element.objects.filter(id__exact=self.id)[0]
            
        for key,value in self.cleaned_data.items():
            if hasattr(e, key):
                e.__setattr__(key, value)
                
        e.owner = User.objects.get(pk=self.cleaned_data['owner'])
        e.section = Section.objects.get(pk=self.cleaned_data['section'])
        e.etype = tp
        e.save()
        for g in self.cleaned_data['groupAdd']:
            e.group.add(g)
        for g in self.cleaned_data['groupRmv']:
            e.group.remove(g)
                  
        return e
